<?php

/**
 * Created by PhpStorm.
 * User: wangan
 * Date: 2018/7/27
 * Time: 17:55
 */
class http
{
    const HOST = '0.0.0.0';
    const PORT = 8812;

    public $http = null;
    public function __construct()
    {
        $this->http = new swoole_http_server(self::HOST, self::PORT);
        $this->http->set([
            'worker_num'=>4 ,//worker process num
            'task_worker_num'=>4
        ]);

        $this->http->on('WorkerStart', [$this,'onWorkerStart']);
        $this->http->on('request', [$this,'onRequest']);
        $this->http->on('task', [$this,'onTask']);
        $this->http->on('finish', [$this,'onFinish']);
        $this->http->on('close', [$this,'onClose']);

        $this->http->start();

    }

    public function onWorkerStart(swoole_server $server, $worker_id){
        // 定义应用目录
        define('APP_PATH', __DIR__ . '/../application/');
        // 加载基础文件 ThinkPHP 引导文件
        //require __DIR__ . '/../thinkphp/base.php';
        require __DIR__ . '/../thinkphp/start.php';
    }

    /**
     * request 回调
    */
    public function onRequest($request, $response){
        $_SERVER = [];
        if($request->server){
            foreach ($request->server as $key => $val){
                $_SERVER[strtoupper($key)] = $val;
            }
        }
        if($request->header){
            foreach ($request->header as $key => $val){
                $_SERVER[strtoupper($key)] = $val;
            }
        }
        $_GET = [];
        if($request->get){
            foreach ($request->get as $key => $val){
                $_GET[$key] = $val;
            }
        }
        $_POST = [];
        if($request->post){
            foreach ($request->post as $key => $val){
                $_POST[$key] = $val;
            }
        }
        $_POST['swoole_http_server'] = $this->http;
        ob_start();
        try{
            // 执行应用并响应
            think\Container::get('app')
                ->run()
                ->send();
        }catch (\Exception $exception){
            //todo
        }
        $res = ob_get_contents();
        ob_end_clean();
        $response->end($res);
    }

    /**
     * @param $data ['method']：方法  $data['data']：参数
    */
    public function onTask(swoole_server $serv, $task_id, $src_worker_id, $data){
        //todo
        try{
            $task = new app\commom\lib\Task();
            $method = $data['method'];
            $task->$method($data['data']);
        }catch (\Exception $exception){
            echo $exception->getMessage();
        }
        echo "worker:{$src_worker_id} task:$task_id finished";
    }

    public function onFinish(){
        //todo
    }

    public function onClose(){
        //todo
    }
}

new http();